﻿#-*-coding:utf-8-*-
# Create your views here.
from crm.models import Members
from crm.models import Salesperson
from crm.models import Agent
from crm.models import Projects
from django.shortcuts import get_object_or_404,render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django import forms
from django.core.paginator import Paginator, InvalidPage


"""调用分配客户显示页"""

def show (request,s_id=""):
    """管理员才有权限"""
    if request.session['level']!="administrators":
        return HttpResponseRedirect('/')
    """获取所有项目数"""
    pj = Projects.objects.order_by('id')
    sp = Salesperson.objects.order_by('id')
    """获取所有代理数"""
    agent = Agent.objects.order_by('id')
    if s_id:
        s_id=int(s_id)
    return render_to_response('allocation.html',{'pj':pj,'sp':sp,'agent':agent,'s_id':s_id})


"""开始分配"""
def allocation_do (request):
    """项目与代理ID,客户ID段.如果没选择则为0"""
    projects_id = request.POST.get('projects_id','0')
    agent_id = request.POST.get('agent_id','0')
    startid = request.POST.get('startid','0')
    endid = request.POST.get('endid','0')
    dagain = request.POST.get('dagain','0')
    """是否删除SALES前把将要删除的SALES的客户分给其它人"""
    s_id = request.POST.get('s_id','0')
    """查找所有SALES列表"""
    allsp = Salesperson.objects.order_by('id')
    """遍历一次SALES与传过来的SALES比较.得到选择分配给多少个SALES"""
    """变量forallsales用来记录一共选了多少个sales"""
    forallsales=0
    listsales=[]
    #用于记录分给哪些选择的sales
    #用于记录剩下未分配的SALES列表
    lastsales=[]

    for allsp in allsp:
        postps='sp['+str(allsp.id)+']'
        postps=request.POST.get(postps,'0')
        if postps=='1':
            forallsales=forallsales+1
            listsales.append(allsp.id)
            lastsales.append(allsp.id)
    """如果一个sales都不选则不用分配,并具返回错误提示要求最少选择一个sales"""
    if forallsales<1:
        pj = Projects.objects.order_by('id')
        sp = Salesperson.objects.order_by('id')
        agent = Agent.objects.order_by('id')
        if s_id:
            s_id=int(s_id)
        return render_to_response('allocation.html',{'pj':pj,'sp':sp,'s_id':s_id,'agent':agent,'errormsg':'you have to choose a sales at least'})

    """开始平均分配
           首先按要求查出所有尚未有sales跟进的customers"""
    """管理员选了按项目分配,只查选中项目的相关客户"""
    if projects_id!='0':
        customers=Members.objects.filter(projects__id=projects_id)
    else:
        if s_id=='0':
            customers=Members.objects.all()
        else:
            customers=Members.objects.filter(salesperson__id=s_id)

    """如果选择是人代理,则只查属于被选代理的客户"""
    if agent_id!='0':
        customers=customers.filter(agent__id=agent_id)
    """如果填写了客户ID段,则只分配此ID段的用户"""
    if startid!='0':
        customers=customers.filter(id__gte=startid,id__lte=endid)
    """是否重新分配,重新分配意思是在上面已有条件下将原已分配的重新分配"""
    if dagain=='0' and s_id=='0':
        customers=customers.filter(salesperson__id=0)
    """customers为最终找出要分配的客户列表"""
    customers = customers.order_by('-id')

    """开始循环分配查出来的客户"""
    """客户总数"""
    allcustomer=int(customers.count())

    """如果有填分配百度比"""
    """forrate用于记录是否有输入百分比"""
    forrate=0
    """ratelist[]表列用于记录各自占的百分比"""
    ratelist=[]
    for rat in listsales:
        sprate='sprate['+str(rat)+']'
        sprate=request.POST.get(sprate,'0')
        """将对应的百分比写入列表"""
        ratelist.append(sprate)
        """如果有百分比不为0."""
        if sprate!='0' and sprate!='':
            #记录输入的百分比个数
            forrate=forrate+1
            #检查输入类型
            try:
                sprate=str(sprate)
                sprate=float(sprate)
            except:
                pj = Projects.objects.order_by('id')
                sp = Salesperson.objects.order_by('id')
                agent = Agent.objects.order_by('id')
                if s_id:
                    s_id=int(s_id)
                return render_to_response('allocation.html',{'pj':pj,'sp':sp,'s_id':s_id,'agent':agent,'errormsg2':'The type of Percentage must be a number and you can choose doesn\'t enter the Percentage then it will be allocated by average'})
        """
        if sprate!='0' and sprate!='':
            sprate=str(sprate)
            sprate=float(sprate)
            allnum=31.0*sprate
            sprate=allnum/100.0
            sprate=ratelist[0]
        """

    startc=0
    nownum=0

    #nownum用于记录此次循环分到第几个人,nownum<=forallsales,以此循环以达到平均分配
    #如果没输入按多少百分比来分配则实行平均分配
    if forrate==0:
        for customer in customers:
            if nownum>=forallsales:
                nownum=0
            member=Members.objects.get(pk=customer.id)
            member.salesperson_id=listsales[nownum]
            nownum=nownum+1
            member.save()
        forallsales=0
            #pass
            #return render_to_response('crm/test.html',{'customers':customers})
    else:
        #按百分比分配 allcustomer 客户总数
        nownum2=0
        salesnum=0
        tempnum=0
        for1num=0
        """ratelist对应的SALES的百分比"""
        for ratelist in ratelist:
            if ratelist!='' and ratelist!='0':
                myallcustomer=allcustomer*int(ratelist)/100
                myallcustomer=tempnum+myallcustomer
                for2=0
                for customer in customers:
                    if for2>=tempnum and tempnum<myallcustomer:
                        member=Members.objects.get(pk=customer.id)
                        member.salesperson_id=lastsales[salesnum]
                        tempnum=tempnum+1
                        for2=for2+1
                        member.save()
                        #if tempnum>myallcustomer:
                            #break
                    else:
                        #break
                        #tempnum=tempnum+1
                        for2=for2+1
                forallsales=forallsales-1
                temp=int(lastsales[salesnum])
                listsales.remove(temp)
            salesnum=salesnum+1


    #没完全填写百分比,将剩下的按平均分配
    if forallsales>0:
        nownum3=0
        temp3=0
        for customer in customers:
            if nownum3>=forallsales:
                nownum3=0
            if temp3>=tempnum:
                member=Members.objects.get(pk=customer.id)
                member.salesperson_id=listsales[nownum3]
                nownum3=nownum3+1
                member.save()
            temp3=temp3+1
    """如果是删SALES前的分配把SALES删掉"""
    if s_id!='0':
        Salesperson.objects.filter(pk=s_id).delete()

    return HttpResponse("Completed distribution,<br /><br /><a href=\"/ulist\">Click here to View the result</a>"+dagain)
    #return render_to_response('tt.html',{'allcustomers':allcustomer,'sprate':tempnum})



